package com.mxw.算法之美.a7二分查找;

public class a02查找第一个值等于给定值的元素 {

    /**
     * 实例调试。int[] nums={1,1,2,2,2,3,3,3,4,5};
     */
    static int left_bound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        // 搜索区间为 [0, 9]
        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                if ((mid == 0) || (nums[mid - 1] != target)) {
                    return mid;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }

}
